package com.tedu.springmvc2.controller;

import com.tedu.springmvc2.mapper.UserMapper;
import com.tedu.springmvc2.pojo.dto.UserDTO;
import com.tedu.springmvc2.pojo.entity.User;
import com.tedu.springmvc2.pojo.vo.UserVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/users")
public class RestfulUserController {

    @Autowired
    UserMapper userMapper;
    //@RequestMapping(value = "/users",method = RequestMethod.POST)
    @PostMapping()
    public String add(UserDTO userDTO){
        System.out.println("开始添加用户:");
        User user = new User();
        BeanUtils.copyProperties(userDTO,user);
        user.setCreated(new java.util.Date());
        return userMapper.insert(user) > 0 ? "添加成功":"添加失败";
    }

   // @RequestMapping(value = "/users",method = RequestMethod.PUT)
    @PutMapping()
    public String update(UserDTO userDTO){
        System.out.println("开始修改用户:");
        User user = new User();
        BeanUtils.copyProperties(userDTO,user);
        return userMapper.update(user) > 0 ? "修改成功":"修改失败";
    }
    //@RequestMapping(value = "/users/{id}",method = RequestMethod.DELETE)
    @DeleteMapping("/{id}")
    public String delete(@PathVariable Integer id){
        System.out.println("开始删除用户:");
        System.out.println(id);
        return userMapper.delete(id) > 0 ? "删除成功":"删除失败";
    }

    //@RequestMapping(value = "/users",method = RequestMethod.GET)
    @GetMapping()
    public List<UserVO> findAll(){
        return userMapper.findAll();
    }

    //@RequestMapping(value = "/users/{id}",method = RequestMethod.GET)
    @GetMapping("/{id}")
    public User findById(@PathVariable Integer id){
        return userMapper.selectById(id);
    }
}
